﻿using Idenmpotency;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Idenmpotency;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yarp.ReverseProxy.Idenmptency;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class YarpIdenmpotencyServiceCollectionExtensions
    {    
        /// <summary>
          /// 使用幂等性请求服务
          /// </summary>
          /// <param name="app"></param>
          /// <param name=""></param>
          /// <returns></returns>
        public static IApplicationBuilder UseYarpIdenmpotency(this IApplicationBuilder appBuilder)
        {
            appBuilder.Use(async (context, next) => {
                var midllerware = new IdenmpotencyMidllerware(appBuilder, next);
                await midllerware.Invoke(context);
            });
            return appBuilder;
        }

        /// <summary>
        /// 添加幂等性请求服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builderAction"></param>
        /// <returns></returns>
        public static IServiceCollection AddYarpIdenmpotency(this IServiceCollection services, Action<YarpIdenmpotencyBuilder> builderAction)
        {
            var aspbuilder = new AspIdenmpotencyBuilder(services);
            var builder = new YarpIdenmpotencyBuilder(aspbuilder);
            builderAction.Invoke(builder);
            if (!aspbuilder.IsBuilt)
            {
                throw new IdenmpotencyException($"Idenmpotency未建造，请检查Build方法是否被调用");
            }
            return services;
        }
    }
}
